package org.ycb.ycbisgod.ycbwoxihuanni.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; // 导入MyBatis-Plus的QueryWrapper
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.ycb.ycbisgod.ycbwoxihuanni.entity.User; // 导入你的用户实体
import org.ycb.ycbisgod.ycbwoxihuanni.mapper.UserMapper; // 导入你的UserMapper接口
import org.ycb.ycbisgod.ycbwoxihuanni.security.MyUserDetails; // 导入你自定义的UserDetails实现

@Service // 将此类标记为Spring Service Bean
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper; // 注入你的UserMapper接口

    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 从数据库中查找用户实体 (使用MyBatis-Plus的查询方式)
        // 使用 QueryWrapper 来构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username); // 查询 username 字段等于传入的 username

        // MyBatis-Plus 的 BaseMapper 提供了 selectOne 方法来查询单个实体
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        // 2. 将用户实体封装成 MyUserDetails 对象并返回
        return new MyUserDetails(user);
    }
}